//
//  Http.m
//  cascade-realm
//
//  Created by QSC on 16/5/24.
//

#import "Http.h"
#import <AFNetworking/AFNetworking.h>
@implementation Http


+ (void)postWithURL:(NSString *)url params:(id)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    [Http postWithURL:url params:params isShowHud:YES isLogin:NO  success:success failure:failure];
}

+ (void)LoginPostWithURL:(NSString *)url params:(id)params
            success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    [Http postWithURL:url params:params isShowHud:YES isLogin:YES success:success failure:failure];
}

+ (void)postWithURL:(NSString *)url params:(id)params isShowHud:(BOOL)isShowHud isLogin:(BOOL)isLogin success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure
{
   
    
    if (isShowHud) {
        [Tool ShowLoading];
      
    }
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSMutableDictionary *header = [self headers];
    
    if (isLogin) {

        [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;" forHTTPHeaderField:@"Content-Type"];

    }else{
        //这两句设置不了application/json，具体原因不明
//         [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//         manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",nil];
         manager.requestSerializer = [AFJSONRequestSerializer serializer];

    }
   
   
    
    NSString *url2 = [NSString stringWithFormat:@"%@%@",Base_url,url];
    
    [manager POST:url2 parameters:params headers:header progress:nil  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (isShowHud) {
            [Tool HideLoading];
        }
        
        NSLog(@"%@----",responseObject);
        NSLog(@"%@----",responseObject[@"msg"]);
        if([responseObject[@"code"] intValue] == 0){
            !success ? : success(responseObject);
        }else{
            !failure ? :failure(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (isShowHud) {
            [Tool HideLoading];
        }
        NSLog(@"%@",error);
        !failure ? :failure(error);
       
    }];
}


+ (void)getWithURL:(NSString *)url params:(NSDictionary *)params success:(HttpSuccessBlock)success failure:(HttpFailureBlock)failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSMutableDictionary *header = [self headers];
    
    
    NSString *url2 = [NSString stringWithFormat:@"%@%@",Base_url,url];
   
    
    [manager GET:url2 parameters:params headers:header progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        if([responseObject[@"code"] intValue] == 0){
            !success ? : success(responseObject);
        }else{
            !failure ? :failure(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        !failure ? :failure(error);
    }];
}



+(NSMutableDictionary *)headers{
    UIDevice * device = [UIDevice currentDevice];
    NSDictionary * info = [NSBundle mainBundle].infoDictionary;
  
    NSMutableDictionary * header = [NSMutableDictionary dictionaryWithDictionary:@{
        @"device-id": device.identifierForVendor.UUIDString,
        @"model": device.model,
        @"platform": @"iOS",
        @"pkg":[NSBundle mainBundle].bundleIdentifier,
//        @"pkg":@"test.cusmofusion.ios",
        @"ver":info[@"CFBundleShortVersionString"],
        @"p_ver":info[@"CFBundleVersion"],
        @"kst" : @"1",
        @"sys_lan":@"en",
        @"lang":@"en",
       
    }];
    
    
    NSString * token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    if(token != nil){
        header[@"Authorization"] = [NSString stringWithFormat:@"Bearer%@",token];
    }

    return  header;
}




+ (void)uploadFile:(NSData *)data fileName:(NSString *)fileName success:(void(^)(NSString *))success failure:(void(^)(void))failure{
    
    [self getOssPolicy:^(id responseObject) {
        NSDictionary * dic = responseObject[@"data"];

        NSString *host = dic[@"host"];
        
     
        
        NSDictionary * parameters = @{
            @"ossaccessKeyId":dic[@"accessKeyId"],
            @"policy":dic[@"policy"],
            @"signature":dic[@"signature"],
            @"callback":dic[@"callback"],
            @"key":[NSString stringWithFormat:@"%@%@",dic[@"dir"],fileName]
        };
        
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

        [manager POST:host parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            [formData appendPartWithFormData:data name:@"file"];
            
                
        } progress:^(NSProgress * _Nonnull uploadProgress) {

            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
            success(responseObject[@"data"][@"filename"]);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure();
        }];
        
        
        
        
    }];
    
    
}


+ (void)getOssPolicy:(void(^)(id responseObject))success{
    
  
    
    [Http getWithURL:getOssPolicy params:@{} success:^(id  _Nonnull responseObject) {
        !success ? : success(responseObject);
    } failure:^(id  _Nonnull errObject) {
        
    }];
}



+(void)getAppConfig{
    
    
    NSString * ver = [[NSUserDefaults standardUserDefaults] objectForKey:@"ver"];;
    if (ver == nil) {
        ver = @"0";
    }
    
    [Http getWithURL:getAppConfig params:@{@"ver":ver} success:^(id  _Nonnull responseObject) {
        
        if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
            return;
        }
        
        NSArray * items = responseObject[@"data"][@"items"];
        
        NSString * ver = responseObject[@"data"][@"ver"];
        [[NSUserDefaults standardUserDefaults] setObject:ver forKey:@"ver"];
        
        for (NSDictionary *item in items) {
            if ([item[@"name"] isEqualToString:@"google_translation_key"]) {
                CAUserInfo.shared.translation_key = item[@"data"];
            }
        }

    } failure:^(id  _Nonnull errObject) {
        
    }];
    
    
}



+ (void)getTranslate:(NSString *)text sucess:(void(^)(NSString *))success{
    
    
    NSMutableDictionary * allTranslate = [NSMutableDictionary dictionaryWithDictionary:[DBTool getData:@"Translate"]];
    
    
    NSString *languageCode = [NSLocale preferredLanguages][0];
    NSString *countryCode = [NSString stringWithFormat:@"-%@",[[NSLocale currentLocale] objectForKey:NSLocaleCountryCode]];
    if(languageCode){
        languageCode = [languageCode stringByReplacingOccurrencesOfString:countryCode withString:@""];
    }


    NSString * key = [NSString stringWithFormat:@"%@--%@",text,languageCode];
    if (allTranslate[key] != nil) {
        success(allTranslate[key]);
        return;
    }
    
    if (CAUserInfo.shared.translation_key == nil) {
        [Http getAppConfig];
        return;
    }

    NSDictionary *params = @{
        @"key": CAUserInfo.shared.translation_key,
        @"target":languageCode,
        @"q":text,
        @"format":@"text"
    };
  
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 10.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager GET:translationUrl parameters:params headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
   
        NSArray * arr = responseObject[@"data"][@"translations"];
        
        if (arr != nil && arr.count > 0) {
            NSString * result = arr[0][@"translatedText"];
            success(result);
            
            allTranslate[key] = result;
            [DBTool saveData:allTranslate tag:@"Translate"];
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
 
    }];

}


static NSString * lan_id = @"0";
static NSInteger sec_id = 0;
+ (void)PostLogWithPage:(NSString *)page{
    
    NSString *tm = [NSString stringWithFormat:@"%.0f",[[NSDate date] timeIntervalSince1970]];
    UIDevice * device = [UIDevice currentDevice];
    NSDictionary * info = [NSBundle mainBundle].infoDictionary;
    sec_id = sec_id + 1;
    if ([page isEqualToString:@"lanuch"]) {
        lan_id = tm;
    }
    
    NSString *languageCode = [NSLocale preferredLanguages][0];
    NSString *countryCode = [NSString stringWithFormat:@"-%@",[[NSLocale currentLocale] objectForKey:NSLocaleCountryCode]];
    if(languageCode){
        languageCode = [languageCode stringByReplacingOccurrencesOfString:countryCode withString:@""];
    }
    NSString *userId =  CAUserInfo.shared.userInfo.userId;
    if (userId == nil) {
        userId = @"";
    }
    NSString * country = CAUserInfo.shared.userInfo.country;
    if (country == nil) {
        country = @"";
    }
    
    NSDictionary *dic = @{
        @"data":@[
            @{
                @"page":page,@"event":@"pv",@"tm":tm
            }
        ],
        @"log_type":@"event",
        @"subtype":@"global_behavior",
        @"behavior":@"event",
        @"device-id":device.identifierForVendor.UUIDString,
        @"user_id":userId,
        @"pkg":[NSBundle mainBundle].bundleIdentifier,
        @"chn_id":@"",
        @"ver":info[@"CFBundleShortVersionString"],
        @"platform":@"iOS",
        @"model":@"iPhone",
        @"p_ver":info[@"CFBundleVersion"],
        @"lan_id":lan_id,
        @"sec_id":[NSString stringWithFormat:@"%ld",(long)sec_id],
        @"sys_lan":countryCode,
        @"country":country,
        @"tm":tm,
        @"utm_source":@"",@"af_adgroup_id":@"",@"af_adset":@"",@"af_adset_id":@"",
        @"af_status":@"",@"af_agency":@"",@"af_channel":@"",@"campaign":@"",@"campaign_id":@""
        
    };
    NSArray * array = [NSArray arrayWithObject:dic];
  

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    [manager POST:logUrl parameters: array headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"logpage---%@",page);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    }];
 

   

    
}

@end
